"""Performance record API endpoints."""

from datetime import date
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
from sqlalchemy.orm import Session

from ...deps import get_current_user
from ....db.sync_session import get_sync_db
from ....models.user import User
from ....schemas.performance_record import (
    PerformanceImportResult,
    PerformanceMonthlySummary,
    PerformanceRecordResponse,
)
from ....services.performance_service import PerformanceService

router = APIRouter()


@router.post("/import", response_model=PerformanceImportResult)
async def import_performance_records(
    file: UploadFile = File(...),
    db: Session = Depends(get_sync_db),
    _current_user: User = Depends(get_current_user),
) -> PerformanceImportResult:
    """Import performance records from Excel file.

    Expected Excel columns:
    - 姓名 (Name)
    - 日期 (Date)
    - 成交次数 (Deals Count)
    - 陪同看房次数 (Showings Count)
    - 新增客户 (New Customers)
    - 客户回访次数 (Follow-up Visits)

    The daily reward is automatically calculated as:
    MIN(deals×10 + showings×5 + new_customers×5 + followups×5, 100)
    """
    # Validate file extension
    if not file.filename or not file.filename.endswith((".xlsx", ".xls")):
        raise HTTPException(status_code=400, detail="Only Excel files (.xlsx, .xls) are allowed")

    service = PerformanceService(db)
    result = await service.import_from_excel(file)

    return result


@router.get("/records", response_model=list[PerformanceRecordResponse])
def get_performance_records(
    user_id: Annotated[Optional[int], Query(description="Filter by user ID")] = None,
    start_date: Annotated[Optional[date], Query(description="Start date filter")] = None,
    end_date: Annotated[Optional[date], Query(description="End date filter")] = None,
    db: Session = Depends(get_sync_db),
    _current_user: User = Depends(get_current_user),
) -> list[PerformanceRecordResponse]:
    """Get performance records with optional filters."""
    service = PerformanceService(db)
    records = service.get_records(user_id, start_date, end_date)
    return [PerformanceRecordResponse.model_validate(r) for r in records]


@router.get("/stats/monthly", response_model=list[PerformanceMonthlySummary])
def get_monthly_stats(
    year: Annotated[int, Query(description="Year")],
    month: Annotated[int, Query(ge=1, le=12, description="Month (1-12)")],
    user_id: Annotated[Optional[int], Query(description="Filter by user ID")] = None,
    db: Session = Depends(get_sync_db),
    _current_user: User = Depends(get_current_user),
) -> list[PerformanceMonthlySummary]:
    """Get monthly performance statistics aggregated by user.

    Returns summary including:
    - Total counts for each activity type
    - Total reward amount
    - Average daily reward
    - Number of working days
    """
    service = PerformanceService(db)
    summary = service.get_monthly_summary(year, month, user_id)
    return summary


@router.get("/stats/top-earners")
def get_top_earners(
    year: Annotated[int, Query(description="Year")],
    month: Annotated[int, Query(ge=1, le=12, description="Month (1-12)")],
    limit: Annotated[int, Query(ge=1, le=100, description="Number of top earners")] = 10,
    db: Session = Depends(get_sync_db),
    _current_user: User = Depends(get_current_user),
) -> list[dict[str, object]]:
    """Get top earners for a specific month.

    Returns the top N employees ranked by total monthly reward.
    """
    service = PerformanceService(db)
    top_earners = service.get_top_earners(year, month, limit)
    return top_earners


@router.delete("/records/{record_id}")
def delete_performance_record(
    record_id: int,
    db: Session = Depends(get_sync_db),
    _current_user: User = Depends(get_current_user),
) -> dict[str, str]:
    """Delete a performance record.

    Useful for correcting import errors or removing duplicate entries.
    """
    service = PerformanceService(db)
    success = service.delete_record(record_id)

    if not success:
        raise HTTPException(status_code=404, detail="Record not found")

    return {"message": "Record deleted successfully"}


@router.get("/dashboard")
def get_performance_dashboard(
    year: Annotated[int, Query(description="Year")],
    month: Annotated[int, Query(ge=1, le=12, description="Month (1-12)")],
    db: Session = Depends(get_sync_db),
    _current_user: User = Depends(get_current_user),
) -> dict[str, object]:
    """Get performance dashboard data for visualization.

    Returns:
    - Top 10 earners
    - Activity breakdown (total deals, showings, new customers, followups)
    - Monthly trends
    """
    service = PerformanceService(db)

    # Get top earners
    top_earners = service.get_top_earners(year, month, limit=10)

    # Get overall monthly summary
    monthly_summary = service.get_monthly_summary(year, month)

    # Calculate activity breakdown
    total_deals = sum(s.total_deals for s in monthly_summary)
    total_showings = sum(s.total_showings for s in monthly_summary)
    total_new_customers = sum(s.total_new_customers for s in monthly_summary)
    total_followups = sum(s.total_followups for s in monthly_summary)
    total_reward = sum(s.total_reward for s in monthly_summary)

    return {
        "top_earners": top_earners,
        "monthly_summary": [s.dict() for s in monthly_summary],
        "activity_breakdown": {
            "total_deals": total_deals,
            "total_showings": total_showings,
            "total_new_customers": total_new_customers,
            "total_followups": total_followups,
            "total_reward": total_reward,
        },
    }
